package com.example.securitydemo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * 未登录时返回json信息的配置
 */
public class DemoAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
//        String message = authException.getLocalizedMessage();
        String message = "登录信息已过期，请重新登录";
        DemoResult demoResult = new DemoResult();
        demoResult.setCode(-1);
        demoResult.setMessage(message);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(demoResult);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
